package cn.e3.cart.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.e3.cart.service.AddCartToRedis;
import cn.e3.pojo.TbItem;
import cn.e3.pojo.TbUser;
import cn.e3.service.ItemService;
import cn.e3.utils.CookieUtils;
import cn.e3.utils.E3Result;
import cn.e3.utils.JsonUtils;

@Controller
public class CartController {
	@Value("${COOKIE_EXPIRE_TIME}")
	private int COOKIE_EXPIRE_TIME;
	@Autowired
	private ItemService itemService;
	@Autowired
	private AddCartToRedis addCartToRedis;
	@RequestMapping("/cart/add/{itemId}")
	public String getCartlistFromCookie(@PathVariable Long itemId,@RequestParam(defaultValue="1")Integer num
			,HttpServletRequest request,HttpServletResponse response){
		/*
		 * 判断用户是否登录，有拦截器中的request获得
		 */
		TbUser user=(TbUser) request.getAttribute("user");
		//判断user是否存在
		if(user!=null){
			//此时用户已登录，将购物侧存入redis,调用服务
			E3Result e3Result = addCartToRedis.addCart(user.getId(), itemId, num);
			//返回
		return	"cartSuccess";
			
		}
		//从cookie中判断商品是否存在
		String json = CookieUtils.getCookieValue(request, "cart", true);
		//将json转化为list<item>集合
		List<TbItem> list=new ArrayList<TbItem>();
		//设立标识符，判断是否找到相同商品
		boolean flag=true;
		if(StringUtils.isNotBlank(json)){
			 list = JsonUtils.jsonToList(json, TbItem.class);
			 //遍历list集合，判断有无重复商品
			 for (TbItem tbItem : list) {
				 if(tbItem.getId()==itemId.longValue()){
					 tbItem.setNum(tbItem.getNum()+num);
					 flag=false;
					 break;
				 }
			 }
		}
		//没有找到相同商品，根据id查询商品，添加到json串中
		if(flag){
			//查询商品
			TbItem tbItem = itemService.selectItemById(itemId);
			//设置其数量
			tbItem.setNum(num);
			//设置其图片，只需要一张图片
			String image = tbItem.getImage();
			String[] split = image.split(",");
			tbItem.setImage(split[0]);
			//将其加入list集合
			list.add(tbItem);
		}
		//将list集合转化为json串
		String jsonList = JsonUtils.objectToJson(list);
		//将其写回cookie中
		CookieUtils.setCookie(request, response, "cart", jsonList, COOKIE_EXPIRE_TIME, true);
		return "cartSuccess";
	}
	@RequestMapping("/cart/cart")
	public String getCartList(HttpServletRequest request,HttpServletResponse response){
		//判断是否登录
		TbUser user = (TbUser) request.getAttribute("user");
		if(user!=null){
			//已经登录，将cookie中的购物车合并
			//获取cookie中的购物车
			String json = CookieUtils.getCookieValue(request, "cart");
			//将json转换为list
			List<TbItem> list = JsonUtils.jsonToList(json, TbItem.class);
			//调用服务层的方法，合并购物车
			 addCartToRedis.merge(user.getId(),list);
			//取出商品返回逻辑视图
			List<TbItem> list2 = addCartToRedis.showCart(user.getId());
			//将其放入requst域中
			request.setAttribute("cartList", list2);
			//清除cookie
			CookieUtils.setCookie(request, response, "cart", "");
			//返回逻辑视图
			return "cart";
		}
		//cookie中取出商品
		String json = CookieUtils.getCookieValue(request, "cart", true);
		//json转换为对象list
		List<TbItem> list = JsonUtils.jsonToList(json, TbItem.class);
		//将list返回
		request.setAttribute("cartList", list);
		return "cart";
	}
	@RequestMapping("/cart/update/num/{itemId}/{num}")
	@ResponseBody
	public E3Result changeNum(@PathVariable Long itemId,@PathVariable Integer num,
			HttpServletRequest request,HttpServletResponse response){
		//判断是否登录
		TbUser user = (TbUser) request.getAttribute("user");
		if(user!=null){
			//修改的redis中的数量
			//调用服务层
			return 	addCartToRedis.changeNum(user.getId(), itemId, num);
			
		}
		//cookie中拿到内容
		String json = CookieUtils.getCookieValue(request, "cart", true);
		//将json转换为集合对象
		List<TbItem> list = JsonUtils.jsonToList(json, TbItem.class);
		//遍历集合，获取id相同的产品
		for (TbItem tbItem : list) {
			if(tbItem.getId()==itemId.longValue()){
				tbItem.setNum(num);
				break;
			}
		}
		//将集合写回json
		String jsonList = JsonUtils.objectToJson(list);
		//将json写回cookie
		CookieUtils.setCookie(request, response, "cart", jsonList, COOKIE_EXPIRE_TIME, true);
		return E3Result.ok();
	}
	@RequestMapping("/cart/delete/{itemId}")
	public String deleteCart(@PathVariable Long itemId,HttpServletRequest request,
			HttpServletResponse response){
		//获得登录信息
		TbUser user = (TbUser) request.getAttribute("user");
		//判断是否登录
		if(user!=null){
			//删除该商品
			//调用服务层
		return 	addCartToRedis.delete(user.getId(), itemId);
		}
		//cookie中拿到信息
		String json = CookieUtils.getCookieValue(request, "cart", true);
		//转为list结合
		List<TbItem> list = JsonUtils.jsonToList(json, TbItem.class);
		//遍历集合
		for (TbItem tbItem : list) {
			if(tbItem.getId()==itemId.longValue()){
				//移除
				list.remove(tbItem);
				break;
			}
		}
		//list转回json
		String jsonList = JsonUtils.objectToJson(list);
		//写回cookie
		CookieUtils.setCookie(request, response, "cart", jsonList, COOKIE_EXPIRE_TIME, true);
		//返回视图，重定向
		return "redirect:/cart/cart.html";
	}
}
